package com.zhku.shoppingspringboot.filter;


import com.alibaba.fastjson.JSON;

import com.zhku.shoppingspringboot.common.BaseContext;
import com.zhku.shoppingspringboot.common.R;
import com.zhku.shoppingspringboot.common.ResultCode;
import com.zhku.shoppingspringboot.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * 检查用户是否已经完成登录
 */
@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
@ServletComponentScan
@Slf4j
public class LoginCheckFilter implements Filter {
    //路径匹配器，支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //1、获取本次请求的URI
        String requestURI = request.getRequestURI();
        //定义不需要处理的请求路径
        String[] urls = new String[]{

                "/user/login",
                "/user/regist",
                "/user/adminRegist",
                "/goods/**",
                "/hot/**",
                "/statistics/**",
                "/categories/**",
                "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs",
                "/favicon.ico",
        };
//        "/user/login",
        //判断当前的请求路径是否需要处理
        if (check(urls, requestURI) ){
            filterChain.doFilter(request, response);
            return;
        }
        //4、判断用户登录状态，如果已登录，则直接放行
        //从请求中获得jwt令牌
        String jwt = null;
        String authorizationHeader = request.getHeader(  "Authorization");
        if (StringUtils.hasLength(authorizationHeader) && authorizationHeader.startsWith("Bearer ")) {
//截取掉"Bearer"前缀，只保留实际的token部分
            jwt = authorizationHeader.substring(7);
        }
        //jwt不存在，未登录，或者已经过期
        if (!StringUtils.hasLength(jwt)) {
            response.getWriter().write(JSON.toJSONString(R.error(ResultCode.NO_LOGIN)));
            return ;
        }
        //解析jwt令牌
        Claims claims;
        try {
            claims = JwtUtils.parseJWT(jwt);
        } catch (Exception e) {
            //解析令牌失败
            response.getWriter().write(JSON.toJSONString(R.error(ResultCode.NO_LOGIN)));
            return;
        }
        //获得当前用户
        Integer id = claims.get("id", Integer.class);
        if (id == null) {
            response.getWriter().write(JSON.toJSONString(R.error(ResultCode.NO_LOGIN)));
            return;
        }

        // 将id放进线
        BaseContext.setCurrentId(id);
        //放行
        filterChain.doFilter(request, response);

    }


    /**
     * 路径匹配，检查本次请求是否需要放行
     *
     * @param urls
     * @param requestURI
     * @return true  不需要处理
     *         false  需要处理
     */
    public boolean check(String[] urls, String requestURI) {
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            if (match) {

                return true;
            }
        }
        return false;
    }
}
